#include <QRegularExpressionMatch>
#include <QStringList>
#include <QFile>

#include "RegularExpression.h"
#include "ui_RegularExpression.h"

RegularExpression::RegularExpression(QWidget *parent)
    : QMainWindow(parent)
    , ui(new Ui::RegularExpression)
{
    ui->setupUi(this);
    setWindowIcon(QIcon(":/myregular/favicon.ico"));
    connect(ui->valid_pushButton, &QPushButton::clicked, this, &RegularExpression::OnValidBtnClicked);
    ui->input_reg_textEdit->setText("(^()$)");


    // 文件路径
    QString filePath = ":/myregular/regularnotes.txt";

    // 读取文件
    QFile file(filePath);
    if (!file.exists())
    {
        qDebug() << "File does not exist:" << filePath;
    }
    else
    {
        if (file.open(QIODevice::ReadOnly | QIODevice::Text))
        {
            QTextStream stream(&file);
            QString contents = stream.readAll();
            ui->notes_textEdit->setText(contents);
            file.close();
        }
        else
        {
            ui->notes_textEdit->append("Error: Cannot open file for reading");
        }
    }
}

RegularExpression::~RegularExpression()
{
    delete ui;
}

void RegularExpression::IsMatched(const QString &qstrPattern, const QString &qstrBeValid)
{
    QRegularExpression regex(qstrPattern);
    QRegularExpressionMatch match = regex.match(qstrBeValid);
    if (match.hasMatch())
    {
        QString qstr_res = QString("<font color='green'>%1, true, match found</font>").arg(qstrBeValid);
        ui->res_textEdit->append(qstr_res);
    }
    else
    {
        QString qstr_res = QString("<font color='red'>%1, false, no match found</font>").arg(qstrBeValid);
        ui->res_textEdit->append(qstr_res);
    }
}

void RegularExpression::OnValidBtnClicked()
{
    QString qstr_pattern = ui->input_reg_textEdit->toPlainText();
    QString qstr_string = ui->input_string_textEdit->toPlainText();
    QString qstr_split = ui->input_delimiter_textEdit->toPlainText();

    if (qstr_pattern.isEmpty() || qstr_string.isEmpty())
    {
        QString qstr_res = QString("<font color='red'>please input pattern and string!</font>");
        ui->res_textEdit->append(qstr_res);
        return;
    }

    if (!qstr_split.isEmpty())
    {
        QStringList list = qstr_string.split(qstr_split, Qt::SkipEmptyParts); // SkipEmptyParts 避免添加空字符串
        for (const QString &str : list)
        {
            IsMatched(qstr_pattern, str);
            qDebug() << str;
        }
    }
    else
    {
        IsMatched(qstr_pattern, qstr_string);
    }
}
